<template>
  <!-- 工程预报右侧父组件 -->
  <div class="lai-water-box">
    <div class="pre-box">
      <div class="title-box">
        <span>来水预报方案信息</span>
        <div class="title-right">
          <font class="iconfont search-file" title="查询" @click="handleSearchScheme"
            >&#xe658;</font
          >
        </div>
      </div>
      <el-table
        :data="state.schemeData"
        border
        style="width: 100%"
        height="100%"
        class="tableClass"
        row-key="id"
        :default-expand-all="true"
      >
        <el-table-column type="expand">
          <template #default>
            <div>
              <el-table
                :data="state.childSchemeList"
                border
                style="width: 100%"
                class="tableClassChild"
                @row-click="handleRowClick"
              >
                <el-table-column align="center" label="单选" width="60">
                  <template #default="scope">
                    <el-radio v-model="state.tableRadio" :label="scope.row.scid">{{ '' }}</el-radio>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="scName"
                  label="
                      工程调度方案名称"
                  align="center"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="ddfsName"
                  label="调度方式名称"
                  align="center"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="status"
                  label="状态"
                  align="center"
                  show-overflow-tooltip
                  width="150"
                >
                  <template #default="{ row }">
                    <div :class="[switchStatusBg(row.status)]">{{ switchStatus(row.status) }}</div>
                    <!-- {{ switchStatus(row.status) }} -->
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  prop="planType"
                  label="创建时间"
                  align="center"
                  show-overflow-tooltip
                /> -->

                <el-table-column label="操作" width="250" align="center" fixed="right">
                  <template #default="{ row }">
                    <div class="handle-box" v-if="row?.scBelong != 0">
                      <font
                        v-if="row.status == 2 || row.status == 0 || row.status == 5"
                        class="iconfont"
                        title="计算"
                        @click="handleComput(row)"
                        >&#xe609;</font
                      >
                      <font v-else :class="['iconfont']" title="计算中">&#xe629;</font>
                      <font
                        v-if="row.status == 2 || row.status == 5"
                        class="iconfont"
                        title="加载计算成果"
                        @click="handleLoadingRes(row)"
                        >&#xe65c;</font
                      >
                      <!-- <div v-if="row.status != 2" class="div-width"></div> -->
                      <!-- <font class="iconfont" title="说明">&#xe67d;</font> -->
                      <font class="iconfont" title="编辑" @click="handleAddPlan(row)"
                        >&#xe654;</font
                      >
                      <font class="iconfont" title="删除" @click="handlePlanDelete(row)"
                        >&#xe662;</font
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="new-file-box">
                <el-button type="primary" @click="handleAddPlan({})">
                  <font class="iconfont">&#xe626;</font>
                  新增
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="isDispach" label="单选" align="center" show-overflow-tooltip /> -->
        <el-table-column
          prop="scName"
          label="方案名称"
          align="center"
          show-overflow-tooltip
          width="180"
        />
        <el-table-column
          prop="reportType"
          label="方案类型"
          align="center"
          show-overflow-tooltip
          width="180"
        />
        <el-table-column
          prop="yrPerd"
          label="预热期"
          align="center"
          show-overflow-tooltip
          width="70"
        />
        <el-table-column
          prop="yjPerd"
          label="预见期"
          align="center"
          show-overflow-tooltip
          width="70"
        />
        <el-table-column prop="fcTime" label="预报时间" align="center" show-overflow-tooltip />
        <el-table-column prop="fcTime" label="模型" align="center" show-overflow-tooltip>
          <template #default>
            <el-select
              v-model="state.modelValue"
              class="m-2"
              placeholder="请选择"
              size="small"
              @change="handleChangeSelect"
            >
              <el-option
                v-for="item in state.typesArr"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column width="50" align="center" fixed="right">
          <template #default> </template>
        </el-table-column> -->
      </el-table>
    </div>
    <div class="title">
      <span class="scDtil-font">方案详情</span>
      <!-- {{ state.scNameTitle ? '-' + state.scNameTitle : '' }} -->
    </div>
    <div class="bottom-box">
      <el-tabs v-model="state.activeName" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane label="预报方案信息" name="first">
          <planAttribute :scId="state.schemeScid" />
        </el-tab-pane>
        <el-tab-pane label="工程调度信息" name="second">
          <projectDispach
            :itemRow="{
              watershedId: props.watershedId,

              parentScheme: state.schemeData,

              model: state.valPlan,

              row: state.rowData
            }"
            ref="projectDispachRef"
          />
        </el-tab-pane>
        <el-tab-pane label="计算进度" name="third" v-if="state.tabsFourth">
          <computProgress
            :map="props.map"
            :scid="state.childScid"
            @refreshScheme="handleRefreshList"
            ref="computProgressRef"
          />
        </el-tab-pane>
        <el-tab-pane label="计算结果" name="fourth" lazy>
          <computResult
            v-if="state.activeName == 'fourth'"
            :fatherTypeId="state.valPlan"
            :fatherId="state.schemeScid"
            :watershedId="props.watershedId"
            :childScid="state.childScid"
            ref="computResultRef"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 新建、修改弹框 -->
    <planDialog ref="planDialogRef" @closeForm="handleCloseForm" />
    <reservoir-dialog ref="reservoirDialog" />
  </div>
  <forecastScheme
    ref="forecastSchemeRef"
    :zoneId="props.watershedId"
    @handleSureSave="handleSureSave"
  />
  <loadingDialog ref="loadingDialogRef" />
</template>

<script setup>
import { reactive, ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import emitter from '@/utils/bus'
// 新建，修改
import planDialog from './cpns/planDialog/index.vue'
import ReservoirDialog from './cpns/reservoirDialog/index.vue'
// 预防方案信息
import planAttribute from './cpns/planAttribute/index.vue'
// 工程调度信息
import projectDispach from './cpns/projectDispach/index.vue'
// 预报方案列表弹框
import forecastScheme from './cpns/forecastScheme/index.vue'
//计算结果
import computResult from './cpns/computResult/index.vue'
import loadingDialog from './cpns/loadingDialog/index.vue'
//计算进度
import computProgress from './cpns/computProgress/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { divGraphicYellow } from '@/utils/mapUtils'
import {
  useDispatchManage,
  useDispatchManageRowIndex,
  useDispatchManageBlkcd
} from '@/store/modules/dispatch-manage.js'
import { storeToRefs } from 'pinia'
import {
  // 查询方案模型类型
  getCalcModelType
} from '@/services/modules/compute-methods.js'
import {
  childrenSchemes,
  deleteManualDispatchScheme,
  manualCalculate,
  getEigResult,
  // 父方案列表
  getDispatchSchemesList,
  // 查询方案详情
  getDispatchSchemeInfo
} from '@/services/modules/dispatch-manage'
const props = defineProps({
  watershedId: {
    type: String,
    // 默认大汶河流域
    default: '1'
  },
  map: {
    type: String,
    default: '1'
  },
  selectName: {
    type: String,
    default: '实测预报降雨'
  }
})
const loadingDialogRef = ref(null)
const state = reactive({
  childScid: '',
  typesArr: [],
  childSchemeList: [],
  schemeScid: '',
  schemeData: [],
  modelValue: '',
  openChild: true,
  activeName: 'first',
  valPlan: {},
  // 每一行选中
  tableRadio: '',
  rowIndex: '',
  tabsFourth: true
  // tabsThird: false
})
const planDialogRef = ref(null)
const reservoirDialog = ref(null)
const computProgressRef = ref(null)
const forecastSchemeRef = ref(null)
const computResultRef = ref(null)
const projectDispachRef = ref(null)

// 根据计算状态半段文字颜色
function switchStatusBg(val) {
  switch (val) {
    case 0:
      return 'info'
    case 1:
      return 'primary'
    case 2:
      return 'success'
    case 3:
      return 'lrdata'
    case 4:
      return 'primary'
    case 5:
      return 'success'
    default:
      return 'info'
  }
}
//
function switchStatus(status) {
  switch (status) {
    case 0:
      return '未计算'
    case 1:
      return '计算中'
    case 2:
      return '计算完成'
    case 3:
      return '数据录入'
    case 4:
      return '水动力计算中'
    case 5:
      return '水动力计算完成'
    default:
      return '未计算'
  }
}
// 点击计算进度tab显示图例
function handleClick(val) {
  console.log(val, '计算进度')
  let a = ''
  if (val == 'fourth') {
    a = 'second'
  } else {
    a = ''
  }
  emitter.emit('switchLegend', a)
  computProgressRef.value.whetherLoadingMap(val)
}
// 查询方案模型类型
const init = () => {
  return new Promise((resolve, reject) => {
    getCalcModelType().then((res) => {
      if (res.code == 200) {
        state.typesArr = res.data
        // handleChangeSelect(state.typesArr[0]?.id)

        resolve(state.typesArr)
      }
    })
  })
}
// watch(
//   () => {
//     props.selectName
//   },
//   async () => {
//     // 获取方案列表
//     state.schemeList = []

//     await acceptSchemesList()

//     handleRowClick(state.schemeList[0] || {})
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )

//获取父方案列表 默认选中第一个父方案
function acceptDefault() {
  return new Promise((resolve, reject) => {
    if (props.selectName == '实测预报降雨') {
      getDispatchSchemesList({ zoneId: props.watershedId, reportType: 0, schemeName: '' }).then(
        (res) => {
          if (res.code == 200) {
            // debugger
            // handleSureSave(res.data[useDispatchManageRowIndex().rowIndex])
            handleSureSave(res.data)
            resolve(res.data)
          }
        }
      )
    } else if (props.selectName == '典型场次') {
      getDispatchSchemesList({ zoneId: props.watershedId, reportType: 1, schemeName: '' }).then(
        (res) => {
          if (res.code == 200) {
            handleSureSave(res.data)
            resolve(res.data)
          }
        }
      )
    } else if (props.selectName == '模拟降雨') {
      getDispatchSchemesList({ zoneId: props.watershedId, reportType: 3, schemeName: '' }).then(
        (res) => {
          if (res.code == 200) {
            handleSureSave(res.data)
            resolve(res.data)
          }
        }
      )
    }
  })
}
onMounted(async () => {
  // await acceptDefault()

  // 获取模型列表
  await init()
})
watch(
  () => {
    props.watershedId
  },
  () => {
    // 获取方案列表
    acceptDefault()
  },
  {
    deep: true,
    immediate: true
  }
)
// 点击某一行，查询当前行计算进度
function handleRowClick(row) {
  state.rowData = row

  // if (row.status == 2) {
  //   state.tabsThird = true
  // } else {
  //   state.tabsThird = false
  // }
  //获取方案id
  state.tableRadio = row?.scid
  state.childScid = row?.scid
  // state.schemeScid = row?.scid
  // state.rowIndex = state.childSchemeList.indexOf(row)
  computProgressRef.value?.getChildIdComputed(row?.scid)

  // storeToRefs(useDispatchManageBlkcd()).scid.value = row?.scid || ''
  // computResultRef.value?.handlePlanItem(row?.scid)
  // projectDispachRef.value?.handlePlanItem(row?.scid)
}
//单方案计算
const handleComput = (row) => {
  state.childScid = row.scid
  state.tableRadio = row?.scid

  manualCalculate({ scid: row.scid }).then((res) => {
    if (res.code === 200) {
      console.log(res)
    }
  })
}
//加载地图计算成果
const handleLoadingRes = (row) => {
  loadingDialogRef.value.handleOpenModal(row)
  // getEigResult({ scid: row.scid, blkcd: '' }).then((res) => {
  //   if (res.code === 200) {
  //     if (res.data.length) {
  //       let arr = []
  //       arr = res.data.filter((item) => {
  //         return item.import == 1
  //       })
  //       // 将数据传入pina根据断面判断popup弹框的数据
  //       storeToRefs(useDispatchManage()).secRes.value = res.data
  //       divGraphicYellow(useDispatchManage().map, arr, 'import')
  //       storeToRefs(useDispatchManage()).scid.value = row.scid
  //       storeToRefs(useDispatchManage()).swTime.value = [row.startTime, row.endTime, arr[0].fcTime]
  //       // storeToRefs(useDispatchManage()).scid.value = state.loadingScheme[0].scid
  //       // handleClose()
  //     }
  //   }
  // })
}
// 获取子方案列表fatherId:父方案id,modelId:选中的模型
const childListToTable = (fatherId, modelId) => {
  return new Promise((resolve, reject) => {
    childrenSchemes({ scid: fatherId, model: modelId }).then((res) => {
      if (res.code === 200) {
        state.childSchemeList = res.data
        if (!state.childSchemeList.length) {
          computResultRef.value?.handlePlanItem('')
        }
        resolve(res.data)
      }
    })
  })
}
// 选择模型
async function handleChangeSelect(val) {
  console.log('抵用')
  state.childSchemeList = []
  state.modelValue = val
  let newArr = state.typesArr.filter((e) => {
    return e.id == val
  })
  storeToRefs(useDispatchManage()).lableVal.value = newArr[0]?.typeName

  // 模型id
  state.valPlan = val

  // 获取子方案列表
  await childListToTable(state.schemeScid, val)
  if (state.childSchemeList.length) {
    handleRowClick(state.childSchemeList[0])
    state.tabsFourth = true
  } else {
    state.tabsFourth = false
    computProgressRef.value?.clearTime()
  }
  // 默认选中第一个
}

// 删除子方案
const handlePlanDelete = (row) => {
  ElMessageBox.confirm('您确定要执行删除此方案吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteManualDispatchScheme({ id: row?.scid }).then((res) => {
        if (res.code == 200) {
          ElMessage.success('删除成功')
          handleChangeSelect(state.valPlan)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

const handleSearchScheme = () => {
  forecastSchemeRef.value.handleOpenModel(props.selectName)
}
function handleCloseForm() {
  handleChangeSelect(state.valPlan)
}
function handleAddPlan(row) {
  planDialogRef.value.handleOpenModal({
    watershedId: props.watershedId,
    // 父方案
    parentScheme: state.schemeData,
    // 模型id
    model: state.valPlan,
    // 编辑或新增
    row: row
  })
}
function handleAddWaterPlan(row) {
  reservoirDialog.value.handleOpenModal({
    watershedId: props.watershedId,
    // 父方案
    parentScheme: state.schemeData,
    // 模型id
    model: state.valPlan,
    // 编辑或新增
    row: row
  })
}

async function handleSureSave(data) {
  data.forEach((item) => {
    if (item.id == useDispatchManageRowIndex().rowIndex) {
      state.schemeData = [item]
      state.schemeScid = item?.id
    }
  })
  // state.schemeData = [val]

  // 默认选中第一个模型类型
  // handleChangeSelect(state.typesArr[0]?.id)
  // 选中父方案 查看详情
  await init()
  acceptDispatchInfo()
}
// 查询父方案详情 获取存在的模型
async function acceptDispatchInfo() {
  getDispatchSchemeInfo({ scid: state.schemeScid, scBelong: 0 }).then((res) => {
    if (res.code == 200) {
      console.log(res.data, '父方案详情')
      let newArr = []
      res.data?.models?.forEach((e) => {
        newArr.push(e?.model)
      })

      state.typesArr = state.typesArr.filter((a) => {
        if (newArr.includes(a.id)) {
          return a
        }
      })
      console.log(state.typesArr[0]?.id, '父请')
      handleChangeSelect(state.typesArr[0]?.id)
    }
  })
}
// 刷新子方案列表
async function handleRefreshList() {
  storeToRefs(useDispatchManageBlkcd()).scid.value = state.schemeScid
  console.log('列表刷新')
  // 获取子方案列表
  await childrenSchemes({ scid: state.schemeScid, model: state.valPlan }).then((res) => {
    if (res.code === 200) {
      state.childSchemeList = res.data
      if (!state.childSchemeList.length) {
        computResultRef.value?.handlePlanItem('')
      }
    }
  })
  // await childListToTable(state.schemeScid, state.valPlan)
  if (state.childSchemeList.length) {
    let newArr = state.childSchemeList.filter((e) => {
      console.log(e.scid, state.tableRadio, '相当')
      if (e.scid == state.tableRadio) {
        return e
      }
    })

    // handleRowClick(newArr[0])
  }
}
emitter.on('refreshChildList', () => {
  childListToTable(state.schemeScid, state.valPlan)
})
</script>
<style lang="less">
// .el-popover.my-popover {
//   width: 960px !important;
//   height: 280px;
//   overflow-y: auto;
//   margin-left: -25px !important;

.new-file-box {
  text-align: right;
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  margin-right: 20px;
}
.handle-box {
  display: flex;
  justify-content: space-around;
  .iconfont {
    width: 30px;
    font-size: 24px;
    font-weight: 400;
    color: #4ea2ec;
    cursor: pointer;
  }
  .iconfont:hover {
    color: #1ad0095b;
  }
  .div-width {
    width: 30px;
    height: 30px;
  }
}
</style>
<style lang="less" scoped>
.lai-water-box {
  width: 100%;
  height: 100%;
  .arrow-color {
    color: #0f83e8;
    font-weight: 600;
    cursor: pointer;
  }
  .pre-box {
    padding: 0 20px;
    height: 460px;
    :deep(.el-table) {
      .el-table__body {
        .el-table__row {
          .el-table_3_column_14 {
            text-align: left;
          }
        }
      }
    }
    .info {
      color: #9a9da2;
    }
    .primary {
      color: #4aa3ff;
    }
    .success {
      color: green;
    }
    .lrdata {
      color: blueviolet;
    }
    .title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      // padding: 0 20px;
      // font-weight: 600;
      font-size: var(--header-fontsize);
      border-bottom: 1px solid var(--fold-border-color);
      font-size: var(--header-fontsize);

      margin-bottom: 10px;
      // margin: 15px;
      // font-weight: 600;
      .title-right {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .iconfont {
          color: #4ea2ec;
          cursor: pointer;
          margin-right: 30px;
        }
        .iconfont:hover {
          color: #0f83e8;
        }
        .new-file {
          font-size: 35px;
        }
        .search-file {
          font-size: 24px;
        }
      }
    }
    .tableClass {
      height: calc(100% - 50px) !important;
      .tableClassChild {
        height: 250px;
        // height: 100%;
        :deep(.el-table__body) {
          .el-table__row {
            .el-table_9_column_41 {
              text-align: left;
            }
          }
        }
      }
    }
  }
  .title {
    line-height: 40px;
    margin: 10px 20px 0 20px;
    height: 40px;
    // color: black;
    font-size: var(--header-fontsize);
    // font-weight: 600;
    // font-size: 15px;
    color: #409eff;
    border-bottom: 1px solid var(--fold-border-color);
    margin-bottom: 20px;
    .scDtil-font {
      color: black;
    }
  }
  .bottom-box {
    padding: 0 20px;
    height: calc(100% - 520px);
    .demo-tabs {
      height: 100%;
      :deep(.el-tabs__header) {
        .el-tabs__item {
          // padding: 0 30px;
          font-size: 14px;
          font-weight: 500;
        }
      }
      :deep(.el-tabs__content) {
        height: calc(100% - 80px);
        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
}
</style>
